package com.tripshare.sdk.weixin.api.util;

import java.security.SecureRandom;
import java.util.Random;

/**
 * Created by lumint on 5/19/16.
 */
public class RandomStringUtil {

    private static final char[] symbols;
    private static final Random random = new Random();

    static {
        StringBuilder tmp = new StringBuilder();
//        for (char ch = '0'; ch <= '9'; ++ch)
//            tmp.append(ch);
        for (char ch = 'a'; ch <= 'z'; ++ch)
            tmp.append(ch);
        symbols = tmp.toString().toCharArray();
    }

    public static String nextRandomString(int length) {
        char[] buf = new char[length];
        for (int idx = 0; idx < buf.length; ++idx)
            buf[idx] = symbols[random.nextInt(symbols.length)];
        return new String(buf);
    }

    private static final SecureRandom secureRandom = new SecureRandom();

    /**
     * length是指生成的随机字节数的长度,不是指返回值的长度。<br>
     *
     * <b color=red>这个方法会block线程,不要轻易使用.</b>
     * @param lengthOfBytesWithoutBase64
     * @return 经过base64编码的字符串
     */
    public static String secureRandomString(int lengthOfBytesWithoutBase64) {
        byte bytes[] = new byte[lengthOfBytesWithoutBase64];
        secureRandom.nextBytes(bytes);
        return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
    }

}
